package com.bihu.bihudemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bihu.bihudemo.dao.CommentLikeDao;
import com.bihu.bihudemo.entity.Comment;
import com.bihu.bihudemo.entity.CommentLike;
import com.bihu.bihudemo.entity.dto.LikedCountDTO;
import com.bihu.bihudemo.service.CommentLikeService;
import com.bihu.bihudemo.service.CommentService;
import com.bihu.bihudemo.service.RedisService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * (CommentLike)表服务实现类
 *
 * @author makejava
 * @since 2020-07-16 16:09:13
 */
@Service("commentLikeService")
public class CommentLikeServiceImpl extends ServiceImpl<CommentLikeDao, CommentLike> implements CommentLikeService {


    @Resource
    private RedisService redisService;
    @Resource
    CommentLikeDao commentLikeDao;
    @Resource
    CommentService commentService;

    //将redis的点赞数据取出，持久化到数据库
    @Override
    public  void likedInfoFromRedis2DB(){
        List<CommentLike> commentLikes = redisService.getLikedDataFromRedis();
        if(commentLikes.size()!=0){
            for(CommentLike c :commentLikes){
                Integer id = c.getId();
                if(commentLikeDao.selectById(id)!=null){
                    //数据库中有这条点赞记录,更新这条记录
                    commentLikeDao.updateById(c);
                }else {
                    //插入一条点赞记录
                    commentLikeDao.insert(c);
                }
            }
        }else {
            System.out.println("点赞信息的缓存为空，不用更新");
        }

    }

    //从redis中更新评论的总点赞数到数据库
    @Override
    public void likedNumFromRedis2DB(){
        List<LikedCountDTO> likedCountDTOS = redisService.getLikedCountFromRedis();

        //要是缓存不为空，才更新数据
        if(likedCountDTOS.size()!=0){
            for(LikedCountDTO DTO:likedCountDTOS){
                int cid = DTO.getCid();
                Comment comment = commentService.getById(cid);
                comment.setLikenum(comment.getLikenum()+DTO.getLikeNum());
                commentService.updateById(comment);
            }
        }else {
            System.out.println("点赞总数的缓存为空，不用更新");
        }

    }
}